package com.example.star.view.center;

import androidx.appcompat.app.AppCompatActivity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.star.R;
import com.example.star.adapter.ShoppingCartAdapter;
import com.example.star.entity.ShoppingCart;
import com.example.star.retrofit.ApiClient;
import com.example.star.api_service.ApiShoppingCart;
import com.example.star.view.activity.BuyNowActivity;
import com.example.star.view.activity.SettlementActivity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ShoppingCartActivity extends AppCompatActivity {

    private static final String TAG = "ShoppingCartActivity";
    private ListView listView;
    private ShoppingCartAdapter adapter;
    private List<ShoppingCart> shoppingCartList = new ArrayList<>();
    private CheckBox allCheckBox;
    private Button deleteButton;
    private Button settleButton;
    private TextView totalPriceTextView;
    private TextView emptyCartTextView;
    private List<Call<?>> callList = new ArrayList<>();
    private SwipeRefreshLayout swipeRefreshLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shopping_cart);
        Log.d(TAG, "onCreate: Activity created");

        listView = findViewById(R.id.list_view_shopping_cart);
        adapter = new ShoppingCartAdapter(this, R.layout.item_shopping_cart, shoppingCartList, this);
        listView.setAdapter(adapter);

        allCheckBox = findViewById(R.id.checkbox_all);
        deleteButton = findViewById(R.id.delete_button);
        settleButton = findViewById(R.id.settle_button);
        totalPriceTextView = findViewById(R.id.total_price_text);
        emptyCartTextView = findViewById(R.id.empty_cart_text);
        swipeRefreshLayout = findViewById(R.id.swipeRefreshLayout);

        totalPriceTextView.setText("0");

        // 从 SharedPreferences 中获取用户名
        SharedPreferences sharedPreferences = getSharedPreferences("user_info", MODE_PRIVATE);
        String userName = sharedPreferences.getString("username", "");
        Log.d(TAG, "onCreate: Retrieved userName: " + userName);


        // 根据用户名查询购物车数据
        getShoppingCartData(userName);

        // 设置下拉刷新的监听器
        swipeRefreshLayout.setOnRefreshListener(() -> {
            // 触发刷新时重新获取数据
            getShoppingCartData(userName);
        });

        // 设置下拉刷新的颜色
        swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light);


        listView.setOnScrollListener(new android.widget.AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                // 检查是否可以下拉刷新
                swipeRefreshLayout.setEnabled(isListViewAtTop());
            }
        });
        // 全选复选框点击事件
        allCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                for (ShoppingCart shoppingCart : shoppingCartList) {
                    shoppingCart.setSelected(isChecked);
                }
                adapter.notifyDataSetChanged();
                updateTotalPrice();
            }
        });

        // 删除按钮点击事件
        deleteButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<ShoppingCart> selectedItems = getSelectedItems();
                if (selectedItems.isEmpty()) {
                    showToast("请选择要删除的商品");
                    return;
                }
                shoppingCartList.removeAll(selectedItems);
                adapter.notifyDataSetChanged();
                allCheckBox.setChecked(false);
                showToast("已删除选中商品");

                // 调用API删除数据库中的对应数据
                deleteSelectedItemsFromDatabase(selectedItems);
                updateTotalPrice();
                checkEmptyCart();
            }
        });

        // 结算按钮点击事件
        settleButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<ShoppingCart> selectedItems = getSelectedItems();
                if (selectedItems.isEmpty()) {
                    showToast("请选择要结算的商品");
                    return;
                }

                Intent intent = new Intent(ShoppingCartActivity.this, SettlementActivity.class);
                // 传递已选商品列表
                ArrayList<String> userName = new ArrayList<>();
                ArrayList<String> starName = new ArrayList<>();
                ArrayList<String> perimeterTitles = new ArrayList<>();
                ArrayList<String> prices = new ArrayList<>();
                ArrayList<String> imageResources = new ArrayList<>();
                ArrayList<String> productTypes = new ArrayList<>();
                ArrayList<String> freights = new ArrayList<>();
                ArrayList<String> deliveryAddresses = new ArrayList<>();
                ArrayList<String> quantity = new ArrayList<>();
                ArrayList<String> totalPrice = new ArrayList<>();

                for (ShoppingCart shoppingCart : selectedItems) {
                    userName.add(shoppingCart.getUserName());
                    starName.add(shoppingCart.getStarName());
                    perimeterTitles.add(shoppingCart.getTitle());
                    prices.add(String.valueOf(shoppingCart.getPrices()));
                    imageResources.add(shoppingCart.getImageResource());
                    productTypes.add(shoppingCart.getProductType());
                    freights.add(shoppingCart.getFreight());
                    deliveryAddresses.add(shoppingCart.getDeliveryAddress());
                    quantity.add(String.valueOf(shoppingCart.getQuantity()));
                    totalPrice.add(String.valueOf(shoppingCart.getTotalPrice()));
                }

                intent.putStringArrayListExtra("userName", userName);
                intent.putStringArrayListExtra("starName", starName);
                intent.putStringArrayListExtra("perimeterTitles", perimeterTitles);
                intent.putStringArrayListExtra("prices", prices);
                intent.putStringArrayListExtra("imageResources", imageResources);
                intent.putStringArrayListExtra("productTypes", productTypes);
                intent.putStringArrayListExtra("freights", freights);
                intent.putStringArrayListExtra("deliveryAddresses", deliveryAddresses);
                intent.putStringArrayListExtra("quantity", quantity);
                intent.putStringArrayListExtra("totalPrice", totalPrice);

                startActivity(intent);
            }
        });
    }

    private boolean isListViewAtTop() {
        return listView.getFirstVisiblePosition() == 0 &&
                (listView.getChildAt(0) == null || listView.getChildAt(0).getTop() >= 0);
    }

    private void getShoppingCartData(String userName) {
        Log.d(TAG, "getShoppingCartData: Starting API call for userName: " + userName);
        ApiShoppingCart apiShoppingCart = ApiClient.getApiShoppingCart();
        Call<List<ShoppingCart>> call = apiShoppingCart.getShoppingCartsByuserName(userName);
        callList.add(call);
        call.enqueue(new Callback<List<ShoppingCart>>() {
            @Override
            public void onResponse(Call<List<ShoppingCart>> call, Response<List<ShoppingCart>> response) {
                // 停止刷新动画
                swipeRefreshLayout.setRefreshing(false);
                callList.remove(call);
                if (response.isSuccessful()) {
                    Log.d(TAG, "onResponse: API call successful, updating cart items");
                    shoppingCartList.clear();
                    shoppingCartList.addAll(response.body());
                    adapter.notifyDataSetChanged();
                    updateTotalPrice();
                    checkEmptyCart();
                } else {
                    String errorMessage = getErrorMessage(response);
                    Log.e(TAG, "onResponse: API call failed, error: " + errorMessage);
                    showToast("获取购物车数据失败: " + errorMessage);
                }
            }

            @Override
            public void onFailure(Call<List<ShoppingCart>> call, Throwable t) {
                // 停止刷新动画
                swipeRefreshLayout.setRefreshing(false);
                callList.remove(call);
                Log.e(TAG, "onFailure: Network request failed", t);
                showToast("网络请求失败: " + t.getMessage());
            }
        });
    }

    private void deleteSelectedItemsFromDatabase(List<ShoppingCart> selectedItems) {
        ApiShoppingCart apiShoppingCart = ApiClient.getApiShoppingCart();
        for (ShoppingCart shoppingCart : selectedItems) {
            Call<Void> call = apiShoppingCart.deleteShoppingCartById(shoppingCart.getId());
            callList.add(call);
            call.enqueue(new Callback<Void>() {
                @Override
                public void onResponse(Call<Void> call, Response<Void> response) {
                    callList.remove(call);
                    if (response.isSuccessful()) {
                        Log.d(TAG, "deleteSelectedItemsFromDatabase: ShoppingCart deleted successfully");
                    } else {
                        String errorMessage = getErrorMessage(response);
                        Log.e(TAG, "deleteSelectedItemsFromDatabase: Failed to delete shoppingCart, error: " + errorMessage);
                        showToast("删除商品失败: " + errorMessage);
                    }
                }

                @Override
                public void onFailure(Call<Void> call, Throwable t) {
                    callList.remove(call);
                    Log.e(TAG, "deleteSelectedItemsFromDatabase: Network request failed", t);
                    showToast("网络请求失败: " + t.getMessage());
                }
            });
        }
    }

    public void updateTotalPrice() {
        double totalAmount = 0;
        boolean allSelected = true;
        for (ShoppingCart shoppingCart : shoppingCartList) {
            if (shoppingCart.isSelected()) {
                totalAmount += shoppingCart.getTotalPrice();
            } else {
                allSelected = false;
            }
        }
        totalPriceTextView.setText(String.valueOf(totalAmount));
        allCheckBox.setChecked(allSelected);
    }

    private void checkEmptyCart() {
        if (shoppingCartList.isEmpty()) {
            emptyCartTextView.setVisibility(View.VISIBLE);
            listView.setVisibility(View.GONE);
        } else {
            emptyCartTextView.setVisibility(View.GONE);
            listView.setVisibility(View.VISIBLE);
        }
    }

    private void showToast(String message) {
        Toast.makeText(ShoppingCartActivity.this, message, Toast.LENGTH_SHORT).show();
    }

    private List<ShoppingCart> getSelectedItems() {
        List<ShoppingCart> selectedItems = new ArrayList<>();
        for (ShoppingCart shoppingCart : shoppingCartList) {
            if (shoppingCart.isSelected()) {
                selectedItems.add(shoppingCart);
            }
        }
        return selectedItems;
    }

    private double getSelectedTotalPrice() {
        double totalAmount = 0;
        for (ShoppingCart shoppingCart : shoppingCartList) {
            if (shoppingCart.isSelected()) {
                totalAmount += shoppingCart.getTotalPrice();
            }
        }
        return totalAmount;
    }

    private String getErrorMessage(Response<?> response) {
        try {
            return response.errorBody().string();
        } catch (IOException e) {
            return "未知错误";
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        for (Call<?> call : callList) {
            if (call != null && !call.isCanceled()) {
                call.cancel();
            }
        }
    }
}